<template>
    <div class="enterprise_contract">
        <div class="head_title">签约费率</div>
       <!--  现在不管编辑还是查看，都只能查看了，这里不能再编辑了，需要编辑签约费率的话，到企业签约费率列表去操作  -->
        <div class="table_data">
            <el-table :data="tableData" border style="width: 100%" :header-cell-style="{background:'#f9f9f9'}"  class="tableBox">
                <!-- <el-table-column  type="index" label="序号" width="100"></el-table-column> -->
                <el-table-column  prop="protocol_start_time" label="协议开始日期" width="250"></el-table-column>
                <el-table-column  prop="protocol_end_time" label="协议终止日期" width="250"></el-table-column>
                <el-table-column  prop="standard_rate" label="标准充值费率" ></el-table-column>
                <el-table-column  label="签约协议" width="100">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="loaddown(scope.row.protocol_img)" target="_blank" v-if="scope.row.protocol_img != ''" >下载协议</el-link>
                    </template>
                </el-table-column>
                <el-table-column  label="查看费率" width="100">
                    <!-- 查看费率start -->
                    <template slot-scope="scope" >  
                        <el-button type="primary" @click="look(scope.row.enterprise_facilitator_id)">查看</el-button>
                        <el-dialog title="费率信息" :visible.sync="dialogTableVisible">
                            <span>标准费率：{{enterpriseRate.standard_rate}}</span>

                            <el-table :data="enterpriseRate.rate_list" v-if="enterpriseRate.region_type_name != '不累计'" :header-cell-style="{background:'#f9f9f9'}">
                                <el-table-column property="range" label="费率政策" width="300"></el-table-column>
                                <el-table-column property="region_rate" :label="enterpriseRate.region_type_name" ></el-table-column>
                            </el-table>
                           
                        </el-dialog>
                    </template>
                    <!-- 查看费率end -->
                </el-table-column>
            </el-table>
            
            <!-- 这里为以前的编辑协议部分，这里不展示了，编辑签约费率部分搬到 企业签约费率列表 去了 -->
            <el-table :data="tableData" border style="width: 100%" :header-cell-style="{background:'#f9f9f9'}" v-if="false">
                <el-table-column  type="index" label="序号" width="100"></el-table-column>
                <el-table-column  prop="protocol_start_time" label="协议开始日期" width="250"></el-table-column>
                <el-table-column  prop="protocol_end_time" label="协议终止日期" width="250"></el-table-column>
                <el-table-column  prop="standard_rate" label="标准充值费率" ></el-table-column>
                <el-table-column  label="签约协议" width="100">
                    <template slot-scope="scope">
                        <el-link type="primary" :href="scope.row.protocol_img" target="_blank" v-if="scope.row.protocol_img != ''" >下载协议</el-link>
                    </template>
                </el-table-column>
                <el-table-column  label="查看费率" width="100">
                    <!-- 编辑费率start -->
                    <template slot-scope="scope" >  
                        <el-button type="success" @click="edit(scope.row.enterprise_facilitator_id)">编辑</el-button>
                        <el-dialog :class="down_z_index" title="编辑费率" :close-on-click-modal="false" :visible.sync="editDialogTableVisible" ref="bjfl">
                            <div class="edit_dialog flex flexC flexJ">
                                <div class="edit_protocol flex center">
                                    <div class="left">
                                        <span>*</span>协议时间:
                                    </div>
                                    <div class="right">
                                        <el-date-picker
                                        v-model="enterpriseRate.protocol_time"
                                        value-format="timestamp"
                                        type="datetimerange"
                                        range-separator="-"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        size="mini"
                                        >
                                        </el-date-picker>
                                    </div>
                                </div>
                                <div class="edit_protocol flex center">
                                    <div class="left">
                                        <span>*</span>协议文件:
                                    </div>
                                    <div class="right">
                                        <el-upload
                                            class="flex"
                                            :action="upload_file"
                                            :on-preview="uploadProtocolPreview"
                                            :on-change="uploadProtocolChange"
                                            :on-success="uploadProtocolSuccess"	
                                            :file-list="enterpriseRate.protocolFileList"
                                            >
                                            <el-button size="small" type="primary">点击上传</el-button>
                                        </el-upload>
                                    </div>
                                </div>
                                <div class="edit_protocol flex center">
                                    <div class="left">
                                        <span>*</span>标准费率:
                                    </div>
                                    <div class="right">
                                        <el-input type="text" size="mini" clearable placeholder="请输入标准费率值" ref="standard_rate" v-model="enterpriseRate.standard_rate" ></el-input>
                                    </div>
                                </div>
                                <div class="edit_protocol flex center">
                                    <div class="left">
                                        <span>*</span>费率政策:
                                    </div>
                                    <div class="right">
                                        <el-select v-model="enterpriseRate.region_type" size="mini" @change="updateRegionType" >
                                            <el-option
                                            :selected="enterpriseRate.region_type == item.value"
                                            v-for="item in region_type_list"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                            ></el-option>
                                        </el-select>
                                    </div>
                                </div>
                                <div class="edit_protocol flex flexC" v-show="isShowRegion">
                                    <div class="region_header flex flexJ">
                                        <div><span>*</span>阶梯费率</div>
                                        <div class=" icon flex flexJ">
                                            <i class="el-icon-circle-plus-outline" @click="add_input"></i>
                                            <i class="el-icon-remove-outline" @click="remove_input"></i>
                                        </div>
                                    </div>
                                    <div class="flex flexC flexJp" ref="region_body">
                                        <div class="region_body_input flex flexJ " v-for="(item, index) in enterpriseRate.rate_list" :key="index" >
                                            <div class="left">
                                                <el-input type="text" size="mini" clearable placeholder="请输入起始金额" v-model="item.money_region_start" ></el-input>元 -
                                                <el-input type="text" size="mini" clearable placeholder="请输入截至金额" v-model="item.money_region_end"></el-input>元
                                            </div>
                                            <div class="right">
                                                费率:
                                                <el-input type="text" size="mini" clearable placeholder="请输入阶梯费率" v-model="item.region_rate" />
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="edit_protocol flex center flexRr">
                                    <el-button  @click="editDialogTableVisible = !editDialogTableVisible">取消</el-button>
                                    <el-button type="primary" @click="submitEnterpriseRate">保存</el-button>
                                </div>

                            </div>
                        </el-dialog>
                    </template>
                    <!-- 编辑费率end -->
                </el-table-column>
            </el-table>

            
        </div>
    <modelBox :show="protocolFileShow" @show_box="showModelProtocolFile" v-if="enterpriseRate.protocolFileList.length > 0">
        <div class="flex center enlargeProtocol">
            <div class="protocol_img">
                <img :src="enterpriseRate.protocolFileList[0].img" style="z-index:9999">
            </div> 
        </div>
    </modelBox>



    <div class="head_title"  v-if="enterpriseRate.do_logs.length > 0">操作日志</div>
    <div class="table_data"  v-if="enterpriseRate.do_logs.length > 0">
        <el-table :data="enterpriseRate.do_logs" border stripe :header-cell-style="{background:'#f9f9f9'}" >
            <el-table-column property="facilitator_user_name" label="操作员" width="100"></el-table-column>
            <el-table-column property="do_time" label="操作时间" width="200"></el-table-column>
            <el-table-column property="content_look" label="描述" ></el-table-column>
        </el-table>
    </div>

    </div>


</template>


<script>
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'


export default {
    name:"EnterpriseContract",
    props:{
        type:0,            //编辑类型：0：查看、1：新增、2：编辑
        reset: false,      //keep-alive 重新进来的重新加载
        add_enterprise_id:0,     //针对新增企业时，传过来的企业ID
    },
    data(){
        return{
            dialogTableVisible: false,  //是否打开查看费率弹窗
            editDialogTableVisible: false,      //是否打开编辑费率弹窗
            enterpriseRate: {           //查看企业费率
                standard_rate:'',       //标准费率
                rate_list:[
                    {
                        money_region_start:'',      //阶梯起始金额
                        money_region_end:'',        //阶梯截至金额
                        region_rate:''              //阶梯费率
                    }
                ],           //阶梯费率
                do_logs:[],              //操作日志
                region_type_name: '',    //费率累计方式
                region_type:0,           //累计方式ID
                protocol_time: [],          //协议时间数组
                protocolFileList: [],        //协议上传图片
            },         
            enterprise_id: 0,           //企业ID
            tableData:[],
            region_type_list:[{value:0, label:'不累计'},{value:1, label:'按月累计'},{value:2, label:'按年累计'}],         //费率政策（0：不累计、1：按月累计、2：按年累计）
            isShowRegion: false,        //是否展示阶梯费率
            protocolFileShow: false,        //默认先隐藏协议图片
            select_enterprise_facilitator_id: 0,     //选中的企业服务商费率ID
            down_z_index: []      //降低 z-index 值
        }
       
    },
    computed:{
        upload_file(){
            return  this.$store.getters.uploadFile;
        }
    },
    mounted() {
        if(parseInt(this.type) === 0 || parseInt(this.type) === 2){
            this.enterprise_id = this.$route.query.enterprise_id;
            this.getSignList();
        }
        this.current_path = this.$route.path;
    },
    watch:{
        add_enterprise_id(newVal, oldVal){
            this.enterprise_id = newVal;
            this.getSignList();
        },
        reset(boolen){
            if(boolen){
                this.dialogTableVisible = false;  //是否打开查看费率弹窗
                this.editDialogTableVisible = false;      //是否打开编辑费率弹窗
                this.enterpriseRate = {           //查看企业费率
                    standard_rate:'',       //标准费率
                    rate_list:[
                        {
                            money_region_start:'',      //阶梯起始金额
                            money_region_end:'',        //阶梯截至金额
                            region_rate:''              //阶梯费率
                        }
                    ],           //阶梯费率
                    do_logs:[],              //操作日志
                    region_type_name: '',    //费率累计方式
                    region_type:0,           //累计方式ID
                    protocol_time: [],          //协议时间数组
                    protocolFileList: [],        //协议上传图片
                };         
                this.enterprise_id = 0;           //企业ID
                this.tableData = [];
                this.region_type_list = [{value:0, label:'不累计'},{value:1, label:'按月累计'},{value:2, label:'按年累计'}];         //费率政策（0：不累计、1：按月累计、2：按年累计）
                this.isShowRegion = false;        //是否展示阶梯费率
                this.protocolFileShow = false;        //默认先隐藏协议图片
                this.select_enterprise_facilitator_id = 0;     //选中的企业服务商费率ID
                this.down_z_index =  [];      //降低 z-index 值
                if(parseInt(this.type) === 0 || parseInt(this.type) === 2){
                    this.enterprise_id = this.$route.query.enterprise_id;
                    this.getSignList();
                }
            }
        }
    },
    methods:{
        getFile(url){
            return new Promise((resolve, reject) => {
            axios({
                    method:'get',
                    url,
                    responseType: 'arraybuffer'
                }).then(data => {
                    resolve(data.data)
                }).catch(error => {
                    reject(error.toString())
                })
            })
        },

        /* 下面为查看/编辑协议费率部分 start */
        loaddown(protocol_img){         //下载协议
            const data = protocol_img // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
                const zip = new JSZip()
                const cache = {}
                const promises = []
                data.forEach(item => {
                    const promise = this.getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
                        const arr_name = item.split("/")
                        const file_name = arr_name[arr_name.length - 1] // 获取文件名
                        zip.file(file_name, data, { binary: true }) // 逐个添加文件
                        cache[file_name] = data
                    })
                    promises.push(promise)
                })

                Promise.all(promises).then(() => {
                    zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
                        FileSaver.saveAs(content, "打包下载.zip") // 利用file-saver保存文件
                    })
                })
        },

        showModelProtocolFile(){
            this.protocolFileShow = false;
            console.log('come hererere');
        },
        getSignList(){
            let {code, msg, data} = this.$api.sendSync(this.$mapapi.f_enterpriseSignFacilitator, {enterprise_id : this.enterprise_id});
            if(code != 200 && msg != '暂无数据'){
                this.$message.error(msg);
                return;
            }
            this.tableData = data.list;
            this.enterpriseRate.do_logs = data.do_logs;
        },
        look(enterprise_facilitator_id){        //查看费率
            this.dialogTableVisible = true;       
            let {code, msg, data}   =   this.$api.sendSync(this.$mapapi.f_enterpriseRate, {enterprise_facilitator_id});
            if(code != 200&&code!=501){
                this.$message.error(msg);
                return;
            }
            if(data.protocol_img != ''){
                data.protocolFileList = [{uid:1, img:data.protocol_img, name:'协议文件' }];
            }    
            this.enterpriseRate = data;
            if(data.rate_list.length > 0){
                for(let val of this.enterpriseRate.rate_list){      //将阶梯费率起始、结束金额做成合成一个字段 range
                    val.range = val.money_region_start + '~' + val.money_region_end;
                }
                this.isShowRegion = true;
            }
        },
        edit(enterprise_facilitator_id){         //编辑费率
            let protocol_file_list = [];
            let {code, msg, data}   =   this.$api.sendSync(this.$mapapi.f_enterpriseRate, {enterprise_facilitator_id});
            if(code != 200&&code!=501){
                this.$message.error(msg);
                return;
            }
            if(data.protocol_img != ''){
                data.protocolFileList = [{uid:1, img:data.protocol_img, name:'协议文件' }];
            }else if(data.protocol_img == ''){
                data.protocolFileList = [];
            }

            this.enterpriseRate = data;
            console.log('this.enterpriseRate',this.enterpriseRate);
            //再将协议图片插入数组中
            // this.enterpriseRate.protocolFileList = [];
            if(data.rate_list.length == 0){
                  this.enterpriseRate.rate_list = [{
                        money_region_start:'',      //阶梯起始金额
                        money_region_end:'',        //阶梯截至金额
                        region_rate:''              //阶梯费率
                    }];
            }
            this.editDialogTableVisible = true;
            this.select_enterprise_facilitator_id = enterprise_facilitator_id;
            if(parseInt(data.region_type) > 0)   this.isShowRegion = true;
            if(!data.protocol_time[0]){
                this.enterpriseRate.protocol_time = [];
            }
        },
        add_input(){            //阶梯费率中增加一行阶梯费率input 框，暂设最多5个阶梯
            if(this.enterpriseRate.rate_list.length > 4)    return;
            this.enterpriseRate.rate_list.push({'money_region_start':'', 'money_region_end':'', 'region_rate':''});
        },
        remove_input(){         //阶梯费率中移除最后一行阶梯费率input 框
            if(this.enterpriseRate.rate_list.length === 1)   return;
            this.enterpriseRate.rate_list.pop();
        },
        updateRegionType(){     //切换费率政策时，控制下面的阶梯费率是否显示
            if(this.enterpriseRate.region_type){
                this.isShowRegion = true;
            }else{
                this.isShowRegion = false;
            }
        },
        uploadProtocolPreview(){        //点击上传的协议图片，进行预览
            //将 el-dialog 的 z-index  降级   el-dialog__wrapper
            let el_dialog = document.getElementsByClassName('el-dialog__wrapper');
            let el_dialog_v_modal = document.getElementsByClassName('v-modal');
            el_dialog[0].style.cssText = "z-index : 5";
            el_dialog_v_modal[0].style.cssText = "z-index : 4";
            this.protocolFileShow = true;
        },
        uploadProtocolChange(file, fileList){         

        },
        uploadProtocolSuccess(res){        //图片上传成功之后
            this.enterpriseRate.protocolFileList=[{uid:Date.now(), img:res.data.url, name: res.data.name }];
        },
        submitEnterpriseRate(){         //保存编辑企业费率信息
            let post_data = {};

            if(this.enterpriseRate.standard_rate == ''){
                this.$message.error('企业标准费率不得为空');
                this.$refs.standard_rate.focus();
                return;
            }
            if(this.enterpriseRate.protocol_time && this.enterpriseRate.protocol_time.length > 0){        //如果协议合作时间不为空则传协议合作时间到后台
                post_data.protocol_time = {};
				post_data.protocol_time.protocol_start = this.enterpriseRate.protocol_time[0]/1000;//协议开始时间
                post_data.protocol_time.protocol_end =  this.enterpriseRate.protocol_time[1]/1000;          //协议结束时间
            }
            if(this.enterpriseRate.protocolFileList.length > 0){         //如果协议图片为空，则上传协议图片
                console.log('protocol_file', this.enterpriseRate.protocolFileList);
                post_data.protocol_img = this.enterpriseRate.protocolFileList[0].img;
                console.log('protocol_img', post_data.protocol_img);

            }
            if(parseInt(this.enterpriseRate.region_type) > 0){           //如果费率政策大于0，则传 阶梯费率数据
                post_data.enterprise_region_rate = this.enterpriseRate.rate_list;
            }
            post_data.region_type = this.enterpriseRate.region_type;
            post_data.standard_rate = this.enterpriseRate.standard_rate;
            post_data.enterprise_facilitator_id = this.select_enterprise_facilitator_id;

            let {code, msg}   =   this.$api.sendSync(this.$mapapi.f_saveEnterpriseRate, post_data);
            if(code != 200){
                this.$message.error(msg);
            }else{
                this.$message.success(msg);
            }
            this.getSignList();
            this.editDialogTableVisible = false;
        }

    }
}
</script>
<style lang="less" :scope="true">
    .enterprise_contract{
        margin: 10px;
        padding: 0;
        background: #fff;
        font-size: 14px;

        .enlargeProtocol{
            width: 100%;
            height: 100%;

            .protocol_img{
                margin: 0 auto;
            }
        }

        .head_title{
            width: 70px;
            text-align: right;
            border-left: 2px solid #4280f2;
            
        }
        
        .table_data{
            padding: 20px 0 80px 0;

            .el-table .cell{
                height: 40px;
                line-height: 20px;
                /* 下面三行是用来实现第二行超出文本出现省略号的 */
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
            }
        }

        .el-dialog{
            .el-dialog__body{
                padding:20px;
            }
        }

        .edit_dialog{
            margin: 0 auto;
            z-index: 5;
            .el-dialog__wrapper{
                z-index: 5;
            }
            .downZindex{
                z-index: 5;
            }

            .edit_protocol{
                width: 100%;
                margin-bottom: 14px;
                .region_header{
                    color: #4280f2;
                    .icon{
                        width: 50px;
                        i{
                            width: 20px;
                            font-size: 20px;
                        }
                    }
                }
                .region_body_input{
                    width: 100%;
                    flex-wrap: nowrap;
                    margin-top:10px;
                    .left{
                        width: 65%;
                        .el-input{
                            width:130px;
                        }
                    }
                    .right{
                        width: 32%;
                        .el-input{
                            width:120px;
                        }
                    }
                }

                .left{
                    span{color: red}

                    width: 80px;
                }
                .right{
                    width: 350px;

                    .el-date-editor{
                        width:350px;
                    }
                    .el-input{
                        width:350px;
                    }
                }
            }
        }

    }

</style>